package com.cyy.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.common.domain.BaseEntity;
import com.cyy.common.mapper.MenuMapper;
import com.cyy.common.mapper.RoleMapper;
import com.cyy.common.mapper.RoleMenuMapper;
import com.cyy.common.pojo.entity.Menu;
import com.cyy.common.pojo.entity.Role;
import com.cyy.common.pojo.entity.RoleMenu;
import com.cyy.common.service.RoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限关联表 服务实现类
 * </p>
 *
 * @author 曹云友
 * @since 2024-03-29
 */
@Service
@RequiredArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    private final RoleMapper roleMapper;

    private final MenuMapper menuMapper;

    @Override
    public List<Integer> getRoleMenuIds(Integer roleId) {
        List<RoleMenu> roleMenus = baseMapper.selectList(Wrappers.<RoleMenu>lambdaQuery()
                .select(RoleMenu::getMenuId)
                .eq(RoleMenu::getRoleId, roleId));
        if (CollectionUtil.isEmpty(roleMenus)) {
            return null;
        }

        return roleMenus.stream().map(RoleMenu::getMenuId).toList();
    }

    @Override
    public void updateRoleMenus(Integer roleId, List<Integer> menuIds) {
        // 查询角色是否存在
        Assert.isTrue(roleMapper.exists(Wrappers.<Role>lambdaQuery().eq(BaseEntity::getId, roleId))
                , "参数错误!");


        // 先删再插
        baseMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));

        // 先查询有效的menu
        List<Menu> menus = menuMapper.selectList(Wrappers.<Menu>lambdaQuery()
                .select(BaseEntity::getId)
                .in(BaseEntity::getId, menuIds));

        if (CollectionUtil.isEmpty(menus)) {
            return;
        }

        // 保存
        List<RoleMenu> roleMenus = menus.stream().map(item -> {
            RoleMenu menu = new RoleMenu();
            menu.setRoleId(roleId);
            menu.setMenuId(item.getId());
            return menu;
        }).collect(Collectors.toList());

        this.saveBatch(roleMenus);

    }
}
